package org.ciallo.simplemusicplayer.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.ciallo.simplemusicplayer.R;
import org.ciallo.simplemusicplayer.adapter.SongAdapter;
import org.ciallo.simplemusicplayer.data.model.Song;
import org.ciallo.simplemusicplayer.dialog.SongOptionsDialogFragment;
import org.ciallo.simplemusicplayer.viewmodel.LocalMusicViewModel;
import org.ciallo.simplemusicplayer.viewmodel.SharedViewModel;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jukomu
 * @Description: 显示特定专辑的所有歌曲的 Activity
 * @Package: org.ciallo.simplemusicplayer.activity
 * @Project: SimpleMusicPlayer
 * @name: AlbumSongsActivity
 * @Date: 2025/6/2-23:34
 * @Filename: AlbumSongsActivity
 */
public class AlbumSongsActivity extends AppCompatActivity {

    public static final String EXTRA_ALBUM_ID = "extra_album_id";
    public static final String EXTRA_ALBUM_NAME = "extra_album_name";
    public static final String EXTRA_ALBUM_ARTIST_NAME = "extra_album_artist_name"; // 专辑的艺术家
    public static final String EXTRA_ALBUM_ART_URI = "extra_album_art_uri";

    private long albumId;
    private String albumNameFromIntent;
    private String albumArtistNameFromIntent;
    private String albumCoverUriFromIntent;

    private Toolbar toolbar;
    private CollapsingToolbarLayout collapsingToolbarLayout;
    private ImageView ivAlbumHeaderCover;
    private TextView tvAlbumArtistHeader; // CollapsingToolbarLayout 中的艺术家
    private RecyclerView recyclerViewAlbumSongs;
    private SongAdapter songAdapter;
    private TextView tvEmptySongsInAlbum;
    private FloatingActionButton fabPlayAll;

    private LocalMusicViewModel localMusicViewModel;
    private SharedViewModel sharedViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_album_songs);

        Intent intent = getIntent();
        albumId = intent.getLongExtra(EXTRA_ALBUM_ID, -1L);
        albumNameFromIntent = intent.getStringExtra(EXTRA_ALBUM_NAME);
        albumArtistNameFromIntent = intent.getStringExtra(EXTRA_ALBUM_ARTIST_NAME);
        albumCoverUriFromIntent = intent.getStringExtra(EXTRA_ALBUM_ART_URI);

        if (albumId == -1L || albumNameFromIntent == null) {
            Toast.makeText(this, "无效的专辑信息", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        toolbar = findViewById(R.id.toolbar_album_songs_activity);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }

        collapsingToolbarLayout = findViewById(R.id.collapsingToolbarLayout_album_songs);
        ivAlbumHeaderCover = findViewById(R.id.imageView_album_songs_header_cover);
        tvAlbumArtistHeader = findViewById(R.id.textView_album_songs_artist_name_header);
        recyclerViewAlbumSongs = findViewById(R.id.recyclerView_album_songs_list);
        tvEmptySongsInAlbum = findViewById(R.id.textView_empty_songs_in_album);
        fabPlayAll = findViewById(R.id.fab_album_songs_play_all);

        collapsingToolbarLayout.setTitle(albumNameFromIntent);
        if (albumArtistNameFromIntent != null && !albumArtistNameFromIntent.isEmpty()) {
            tvAlbumArtistHeader.setText(albumArtistNameFromIntent);
            tvAlbumArtistHeader.setVisibility(View.VISIBLE);
        } else {
            tvAlbumArtistHeader.setVisibility(View.GONE);
        }

        Glide.with(this)
                .load(albumCoverUriFromIntent != null ? Uri.parse(albumCoverUriFromIntent) : null)
                .placeholder(R.drawable.default_album_art)
                .error(R.drawable.default_album_art)
                .into(ivAlbumHeaderCover);

        localMusicViewModel = new ViewModelProvider(this).get(LocalMusicViewModel.class);
        sharedViewModel = new ViewModelProvider(this).get(SharedViewModel.class);

        setupRecyclerView();
        observeViewModel();

        fabPlayAll.setOnClickListener(v -> {
            List<Song> currentList = songAdapter.getCurrentList();
            if (currentList != null && !currentList.isEmpty() && sharedViewModel != null) {
                sharedViewModel.playSongAtIndex(new ArrayList<>(currentList), 0);
            } else {
                Toast.makeText(this, "专辑中没有歌曲可播放", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void setupRecyclerView() {
        songAdapter = new SongAdapter(
                (song, position) -> { // OnSongClickListener
                    List<Song> currentList = songAdapter.getCurrentList();
                    if (sharedViewModel != null && currentList != null && !currentList.isEmpty()) {
                        sharedViewModel.playSongAtIndex(new ArrayList<>(currentList), position);
                    }
                },
                (song, anchorView) -> { // OnSongOptionsClickListener
                    SongOptionsDialogFragment.newInstance(song.getId()) // 传递被点击歌曲的ID
                            .show(getSupportFragmentManager(), SongOptionsDialogFragment.TAG);
                }
        );
        recyclerViewAlbumSongs.setLayoutManager(new LinearLayoutManager(this));
        recyclerViewAlbumSongs.setAdapter(songAdapter);
    }

    private void observeViewModel() {
        localMusicViewModel.getSongsByAlbumId(albumId).observe(this, songs -> {
            if (songs != null && !songs.isEmpty()) {
                songAdapter.submitList(songs);
                tvEmptySongsInAlbum.setVisibility(View.GONE);
                recyclerViewAlbumSongs.setVisibility(View.VISIBLE);
                fabPlayAll.show();
            } else {
                songAdapter.submitList(new ArrayList<>());
                tvEmptySongsInAlbum.setVisibility(View.VISIBLE);
                recyclerViewAlbumSongs.setVisibility(View.GONE);
                fabPlayAll.hide();
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
